<?php

use App\Exception\TaskExceptionHandler;
use App\Exception\WsExceptionHandler;
use App\Util\MessageFormatUtil;
use Elite\Infrastructure\Server\Swoole;
use Elite\Infrastructure\Server\Task\Tasker;
use \Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
use \App\Exception\HttpExceptionHandler;
use Swoole\Server\Task;

class WebBootstrap extends \Elite\Bootstrap {

    protected array $beforeStarters = [
        \App\Starter\PathBeforeStarter::class,
        \App\Starter\RouterBeforeStarter::class,
    ];

    protected array $afterStarters = [
        \App\Starter\GlobalMiddlewareAfterStarter::class,
        \Elite\Infrastructure\Starter\RouterAfterStarter::class,
    ];

    public function preload(Swoole $swoole) {
        $this->initConfig(ROOT_DIR . '/config/config.php', $swoole->getEnv());
        $swoole->setStarterTransfer($this->initBeforeStater());
    }

    public function startHttp(Swoole $swoole, Request $request, Response $response) {
        $this->initConfig(ROOT_DIR . '/config/config.php', $swoole->getEnv());
        try {
            $this->bindServer($swoole->getServer())
                ->initHttp($request, $response)
                ->initAfterStarter($swoole->getStarterTransfer())
                ->boot();
        } catch (\Throwable $t) {
            // print_r("err:" . $t->getMessage() . PHP_EOL);
            $handler = new HttpExceptionHandler($request, $response);
            $handler->handle($t);
        }
    }

    public function startWs(Swoole $swoole, \Swoole\WebSocket\Frame $frame) {
        $this->initConfig(ROOT_DIR . '/config/config.php', $swoole->getEnv());
        try {
            $this->bindServer($swoole->getServer())
                ->initLongConnect($swoole, MessageFormatUtil::convertToMessage($frame, $swoole->getFdHolder()))
                ->initAfterStarter($swoole->getStarterTransfer())
                ->boot();
        } catch (\Throwable $t) {
//             print_r("！！！！ERROR！！！！\n" . $t->getMessage() . PHP_EOL);
//             print_r($t->getTraceAsString() . PHP_EOL);
            $handler = new WsExceptionHandler($swoole->getServer()->connections[$frame->fd]);
            $handler->handle($t);
        }
    }

    public function startTask(Swoole $swoole, Tasker $tasker, Task $task) {
        $this->initConfig(ROOT_DIR . '/config/config.php', $swoole->getEnv());
        try {
            $this->bindServer($swoole->getServer())
                ->initTask($task, $tasker)
                ->initAfterStarter($swoole->getStarterTransfer())
                ->boot();
        } catch (\Throwable $t) {
//             print_r("！！！！ERROR！！！！\n" . $t->getMessage() . PHP_EOL);
//             print_r($t->getTraceAsString() . PHP_EOL);
            $handler = new TaskExceptionHandler($tasker, $task);
            $handler->handle($t);
        }
    }

}